/* Copyright (c) 2021 OceanBase and/or its affiliates. All rights reserved.
miniob is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */

//
// Created by WangYunlai on 2022/6/27.
//

#include "common/log/log.h"
#include "sql/operator/order_physical_operator.h"
int OrderPhysicalOperator::compare(const Value &left, const Value &right, const OrderType &order_type) const
{       

        int result = 0;
        if(left.attr_type()==AttrType::NULLS||right.attr_type()==AttrType::NULLS){
                if(left.attr_type()==right.attr_type()){
                        return result;
                }
                if(left.attr_type()==AttrType::NULLS){
                        result=-1;
                }
                else {
                        result=1;
                }
        }
        else {
                result=left.compare(right);
        }
        
        if (order_type == OrderType::O_DESC)
                result = -result;
        return result;
}
int OrderPhysicalOperator::compare(const Value *left_list, const Value *right_list) const
{
        int result = 0;
        for (int i = 0; i < field_num_; i++)
        {
                const Value &left = left_list[i];
                const Value &right = right_list[i];
                const OrderType& order_type=order_types_[i];
                result = compare(left, right,order_type);
                if (result != 0)
                        return result;
        }
        return result;
}
RC OrderPhysicalOperator::next()
{
        if (row_num_ > 0)
        {
                // 取出最小行索引
                int first_value_index = value_index_list_[0];
                // 末尾行前移
                swap(0,row_num_-1);
                // 移除末尾行
                order_value_lists_.pop_back();
                // 获取当前行
                std::vector<Value> current_value = result_value_list_[first_value_index];
                val_tuple_.set_cells(current_value);
                // 行数减一
                --row_num_;
                // 调整小根堆
                adjustMinHeap(0);
                return RC::SUCCESS;
        }
        return RC::RECORD_EOF;
}
RC OrderPhysicalOperator::init()
{
        PhysicalOperator *child = children_[0].get();
        RC rc = RC::SUCCESS;
        //列表初始化
        while ((rc =child->next())==RC::SUCCESS)
        {
                Tuple* tuple=child->current_tuple();
                //初始化结果列表
                std::vector<Value> result_value;
                int cell_num=tuple->cell_num();
                for(int i=0;i<cell_num;i++){
                        Value value;
                        rc=tuple->cell_at(i,value);
                        if(rc!=RC::SUCCESS){
                                return rc;
                        }
                        result_value.push_back(value);
                }
                result_value_list_.push_back(result_value);
                //初始化排序列表
                 Value* order_value=new Value[field_num_];
                for(int i=0;i<field_num_;i++){
                        Field field=order_fields_[i];
                        Value value;
                        rc=tuple->find_cell(TupleCellSpec(field.table_name(),field.field_name()),value);
                        if(rc!=RC::SUCCESS){
                                return rc;
                        }
                        order_value[i]=value;
                }
                order_value_lists_.push_back(order_value);
                //行数加一
                ++row_num_;
        }
        if(rc==RC::RECORD_EOF){
         rc=RC::SUCCESS;
         //构建索引
         value_index_list_=new int[row_num_];
         for(int i=0;i<row_num_;i++){
                value_index_list_[i]=i;
         }
         //小根堆排序
         sort();
        }
        return rc;
}
void OrderPhysicalOperator::sort()
{ // TODO
        for(int i=(row_num_-1)/2;i>=0;i--){
                adjustMinHeap(i);
        }
}
void OrderPhysicalOperator:: swap(int p_index,int target_index){
        //交换索引
        int tmp=value_index_list_[p_index];
        value_index_list_[p_index]=value_index_list_[target_index];
        value_index_list_[target_index]=tmp;
        //交换排序表
        const Value* tmp_val=order_value_lists_[p_index];
        order_value_lists_[p_index]=order_value_lists_[target_index];
        order_value_lists_[target_index]=tmp_val;
}
// 下移调整小根堆
void OrderPhysicalOperator::adjustMinHeap(int index)
{ 
        int left=2*index+1;
        int right=left+1;
        int min_index=index;
        if(left<row_num_){
                const Value* left_value_list=order_value_lists_[left];
                const Value* min_value_list=order_value_lists_[min_index];
                int compare_result=compare(left_value_list,min_value_list);
                if(compare_result<0){
                      min_index=left;  
                }
        }
        if(right<row_num_){
                const Value* right_value_list=order_value_lists_[right];
                const Value* min_value_list=order_value_lists_[min_index];
                int compare_result=compare(right_value_list,min_value_list);
                if(compare_result<0){
                        min_index=right;
                }
        }
        if(min_index==index)return ;
        swap(index,min_index);
        //递归调整
        adjustMinHeap(min_index);
}